var Q = require('q');
var Message = require('../models/message');
const querystring = require("querystring");
var request = require('request');
var robot  = {};



robot.receive = function (option) {
    var socket = option.socket;
    var msg = option.msg;
    var mess = {
        username: "robot",
        receive:msg.username,
        type:5,      //1:对客服讲话,2:对人讲话,3:系统广播,4:大厅全局聊天,5：机器人聊天
        src: '',
        img:  '', //base64图片
        msg: msg.msg,
        time: msg.time || Date.now()
    }

    robot.replay(option).then(function (res) {
        mess.msg = res.data.text;
        savemsg(mess);

    },function (res) {
        res = JSON.parse(res);
        mess.msg = res.data.text || "机器人错误了。";
        savemsg(mess);
        global.logger.info("机器人错误"+JSON.stringify(res));
    });

    function  savemsg(mess) {
        var message = new Message(mess);
        message.save(function (err, mess) {
            if (err) {
                global.logger.error(err)
            }
            global.logger.info(mess)
        });

        socket.emit("message",mess);
    }

}


robot.replay = function (option) {
    var deferred = Q.defer();
    var socket = option.socket;
    var msg = option.msg;
    var req = {
        code:1,
        message:"发送成功",
        data:{}
    }
    if(!socket || !msg){
        process.nextTick(function(){
            req.code = -3;
            req.message = "参数错误";
            deferred.reject(req);
            global.logger.info("参数错误:",JSON.stringify(option));
        });
        return deferred.promise;
    }

    /*    var data = {
     "reqType":0,
     "perception": {
     "inputText": {
     "text": msg.msg
     }
     },
     "userInfo": {
     "apiKey": "46653ff2f959407da57e9ada472ce4f0",
     "userId": msg.username
     }
     }*/
    var data =   querystring.stringify({
        key: '46653ff2f959407da57e9ada472ce4f0',
        info: msg.msg,
        userid:  msg.username
    });

    console.log(data)
    request({
        timeout:5000,    // 设置超时
        headers: {
            "Content-Type": 'application/x-www-form-urlencoded',
        },
        rejectUnauthorized: false,
        method:'POST',    //请求方式
        url:'http://www.tuling123.com/openapi/api',
        form:data
    },function (error, response, body) {
        if (!error && response.statusCode == 200) {
            try {
                req.data = JSON.parse(body);
            }catch (e){
                req.data = body;
            }
            deferred.resolve(req);
        }else{
            req.code = -7;
            req.message = "数据请求错误";
            req.data = error;
            deferred.reject(req)
        }
    });
    return deferred.promise;
}

module.exports = robot;